<template>
  <div class="attend_detail">
    <div class="attend_detail_left">
      <div class="info_detail_title">
        <div class="title_name">{{ detailInfo.overtimeTitle }}</div>
        <div class="title_org">部门：{{ detailInfo.orgName }}</div>
      </div>
      <div class="right_box">
        <div class="attend_main">
          <div class="table_con" ref="table_con">
            <vxe-table
              border
              stripe
              class="mytable-scrollbar"
              highlight-hover-row
              show-overflow
              size="medium"
              height="100%"
              :data="tableData"
              align="center"
              v-if="!load"
              @cell-click="cellClick"
              :span-method="mergeRowMethod"
              :edit-config="{ trigger: 'click', mode: 'cell', activeMethod: activeRowMethod }"
              :column-config="{ resizable: true }"
              :empty-text="emptyText">
              <vxe-table-column field="overtimeDay" title="日期" width="200">
                <template #default="{ row }">
                  <span>{{ row.overtimeDay }}（{{ row.dayOfWeek }}）</span>
                </template>
              </vxe-table-column>
              <vxe-table-column field="timeBucket" title="时段" width="100">
                <template #default="{ row }">
                  <span>{{ row.timeBucket | TimeBucket }}</span>
                </template>
              </vxe-table-column>
              <vxe-table-column field="userList" title="值班人员" min-width="200" :edit-render="{}">
                <template #default="{ row }">
                  <span v-if="detail.saveStatus !== '1' || (detail.saveStatus === '1' && row.userList.length)">
                    {{ row.userList | FilterPerSon }}
                  </span>
                  <span v-else>无</span>
                </template>
                <template #edit="{ row }">
                  <el-select
                    v-model="row.userList"
                    multiple
                    filterable
                    placeholder=""
                    @change="roleChangeEvent"
                    :popper-append-to-body="false"
                    value-key="userName"
                    size="small">
                    <el-option
                      :value="item"
                      :label="item.userName"
                      v-for="item in showMemberList"
                      :key="item.userId"></el-option>
                  </el-select>
                  <!-- <vxe-select
                    v-model="row.userList"
                    clearable
                    transfer
                    @change="roleChangeEvent"
                    multiple
                    :filterable="true"
                    :inputable="true"
                  >
                    <vxe-option
                      :value="item"
                      :label="item.userName"
                      v-for="item in showMemberList"
                      :key="item.userId"
                    ></vxe-option>
                  </vxe-select> -->
                </template>
              </vxe-table-column>
              <vxe-table-column field="remark" title="备注" width="140"></vxe-table-column>
            </vxe-table>
          </div>
        </div>
        <div class="btn_check" v-if="firstType === '0' && detail.saveStatus !== '1'">
          <el-button size="small" type="primary" @click="approvalData('0')" class="btnBorder">暂 存</el-button>
          <el-button size="small" type="danger" @click="approvalData('1')" class="btnBg">提 交</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getPreWeekendDutyDetail, submitaddPreWeekendDuty } from '@apis/api-dailyManage.js'
import moment from 'moment'
export default {
  components: {},
  props: {
    firstType: {
      type: String,
      default: '',
    },
    activeInfo: {
      type: Object,
      default: () => {},
    },
    memberList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      moment: moment,
      applyType: '1',
      timeNow: moment().format('YYYY-MM-DD'),
      model: '',
      reason: '',
      detail: {},
      detailInfo: {},
      dialogShow: false,
      tableData: [],
      load: false,
      originalData: [],
      activeData: {},
      showMemberList: [],
      emptyText: '暂无数据',
    }
  },
  computed: {
    memberActive() {
      if (this.memberList && this.memberList.length && this.activeInfo && this.activeInfo.id) {
        return true
      } else if (this.firstType !== '0' && this.activeInfo && this.activeInfo.id) {
        return true
      } else {
        return false
      }
    },
  },
  watch: {
    memberActive: {
      handler(news) {
        if (news) {
          this.showMemberList = this.memberList
          this.detail = this.activeInfo
          this.getPreWeekendDutyDetail()
        }
      },
      deep: true,
      immediate: true,
    },
  },
  filters: {
    FilterPerSon(val) {
      const arr = []
      if (val && val.length) {
        val.forEach(item => {
          arr.push(item.userName)
        })
        return arr.join(',') || '无'
      }
    },
    TimeBucket(val) {
      switch (val) {
        case '0':
          return '全天'
        case '1':
          return '上午'
        case '2':
          return '下午'
        default:
          break
      }
    },
  },
  created() {},
  mounted() {
    if (this.$route.query.id && this.$route.query.type === '3') {
      this.detail = this.$route.query
      this.getPreWeekendDutyDetail()
    }
  },
  methods: {
    approvalData(type) {
      const arr = []
      this.tableData.forEach((li, i) => {
        li.userList.forEach((li1, i1) => {
          arr.push({
            dayOfWeek: li.dayOfWeek,
            id: this.originalData[i].userList[i1] ? this.originalData[i].userList[i1].id : '',
            overtimeDay: li.overtimeDay,
            overtimeDayId: li.overtimeDayId,
            sort: i1,
            timeBucket: li.timeBucket,
            userId: li1.userId,
            userName: li1.userName,
          })
        })
        if (type === '1' && li.userList.length === 0) {
          arr.push({
            dayOfWeek: li.dayOfWeek,
            id: this.originalData[i].userList[0].id,
            overtimeDay: li.overtimeDay,
            overtimeDayId: li.overtimeDayId,
            sort: 0,
            timeBucket: li.timeBucket,
            userId: '',
            userName: '无',
          })
        }
      })
      const param = {
        id: this.detail.id,
        inputDetailList: arr,
        saveStatus: type,
      }
      submitaddPreWeekendDuty(param).then(res => {
        if (res.code === 0) {
          this.$message.success('成功')
          this.$emit('addSuccess', 'detail')
        }
      })
    },
    getPreWeekendDutyDetail() {
      getPreWeekendDutyDetail({
        id: this.detail.id,
      }).then(res => {
        if (res.code === 0) {
          this.detailInfo = res.data
          this.originalData = JSON.parse(JSON.stringify(res.data.preItemDetailList))
          let data = res.data.preItemDetailList || []
          if (this.firstType === '0') {
            data.forEach(item => {
              const arr = []
              item.userList.forEach(li => {
                this.showMemberList.forEach(li1 => {
                  if (li1.userId === li.userId) {
                    arr.push(li1)
                  }
                })
              })
              item.userList = arr
            })
          } else if (this.firstType === '4' && this.activeInfo.saveStatus !== '1') {
            this.emptyText = '暂无提交'
            data = []
          }
          this.tableData = data || []
        }
      })
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    mergeRowMethod({ row, _rowIndex, column, visibleData }) {
      const fields = ['overtimeDay']
      const cellValue = row.overtimeDay + row.dayOfWeek
      if (fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1]
        let nextRow = visibleData[_rowIndex + 1]
        if (prevRow && prevRow.overtimeDay + prevRow.dayOfWeek === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow.overtimeDay + nextRow.dayOfWeek === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    },
    roleChangeEvent(value) {
      // console.log('value :>> ', value)
    },
    // 设置是否可以编辑
    activeRowMethod({ row, rowIndex }) {
      if (this.firstType === '0' && this.detail.saveStatus !== '1') {
        return true
      }
    },
    cellClick({ row, column }) {
      if (this.detail.saveStatus === '1') return
      if (this.activeData.overtimeDay === row.overtimeDay && this.activeData.timeBucket === row.timeBucket) return
      this.activeData = row
      const arr = this.tableData.filter(item => {
        if (item.overtimeDay === this.activeData.overtimeDay && item.timeBucket !== this.activeData.timeBucket) {
          return true
        } else {
          return false
        }
      })
      const choose = []
      arr.forEach(item => {
        item.userList.forEach(li => {
          choose.push(li.userId)
        })
      })
      const prepare = this.memberList.filter(item => {
        return !choose.includes(item.userId)
      })
      this.showMemberList = prepare
      // console.log('this.showMemberList :>> ', this.showMemberList)
    },
    selectStatus() {},
  },
}
</script>

<style lang="scss" scoped>
.attend_detail {
  height: 100%;
  font-size: 16px;
  display: flex;
  .attend_detail_left {
    height: 100%;
    width: 100%;
  }
  .info_detail_title {
    font-weight: 400;
    padding-left: 20px;
    // text-align: center;
    .title_name {
      text-align: center;
      height: 50px;
      line-height: 50px;
      font-size: 24px;
    }
    .title_org {
      font-weight: 600;
    }
  }
  .right_box {
    height: calc(100% - 100px);
    width: 100%;
    display: flex;
    flex-direction: column;
    margin-top: 10px;
    .attend_main {
      width: 100%;
      padding: 0 20px;
      height: calc(100% - 60px);
      margin: 0 auto;
      flex: 1;
    }
    .table_con {
      height: 100%;
      /deep/.vxe-cell--edit-icon {
        display: none;
      }
      /deep/.el-select {
        width: 100%;
      }
    }
    .btn_check {
      margin-top: 10px;
      margin-right: 10px;
      text-align: center;
    }
  }
  .size_input {
    ::-webkit-outer-spin-button,
    ::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }

    input[type='number']::-webkit-outer-spin-button,
    input[type='number']::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }
  }
}
.branch_dialog {
  /deep/.el-dialog__body {
    padding-left: 20px;
    padding-right: 20px;
    min-height: 0;
    .el-radio {
      margin-right: 20px;
    }
    .el-textarea {
      margin: 20px 0;
    }
    .btn_save {
      text-align: right;
    }
  }
}
</style>
